package com.media.MinioTest;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;

import java.io.*;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Test1 {


    private static MinioClient minioClient =
            MinioClient.builder()
                    .endpoint("http://192.168.121.141:9000")
                    .credentials("minioadmin", "minioadmin123")
                    .build();

    public static void main(String[] args) throws IOException {
        //数据分块
      contextLoads();
        //上传分块文件至minio
        uploadChunks();
        //txt文件分块后保留原格式
//      contextLoads1();
        //合并txt
//      mergeChunks();
    }

    //进行分块
    static void contextLoads() throws IOException {
        //获得上传文件路径
        File uploadFile = new File("C:\\Users\\lingjun\\Videos\\Captures\\Ubuntu18.04.4-x64 - VMware Workstation 16 Player (仅用于非商业用途) 2023-06-04 22-59-06.mp4");

        //分块大小
        int chunkSize = 1024 * 1024 * 5;
        //分块个数
        int chunkNum = (int) Math.ceil(uploadFile.length() * 1.0 / chunkSize);

        System.out.println("分块总数：" + chunkNum);
        //设置缓冲区大小
        byte[] buffer = new byte[1024];

        RandomAccessFile read = new RandomAccessFile(uploadFile, "r");

        //使用RandomAccessFile写入文件
        for (int i = 0; i < chunkNum; i++) {//使用RandomAccessFile读取文件
            System.out.println("分块路径" + i);
            //分块文件路径
            String chunkFilePath = "D:\\test\\" + i;
            //分块文件
            File chunkFile = new File(chunkFilePath);

            System.out.println("分块路径：" + chunkFile);

         /*//分块文件不存在，创建分块文件
         if (!chunkFile.exists()) {
            chunkFile.createNewFile();
         }*/

            //分块文件写入
            RandomAccessFile write = new RandomAccessFile(chunkFile, "rw");

            int len = -1;
            while ((len = read.read(buffer)) != -1) {
                write.write(buffer, 0, len);
                if (chunkFile.length() >= chunkSize) {
                    break;
                }
            }

            write.close();

        }
        read.close();

    }

    //记事本根据字符流分块
    static void contextLoads1() throws IOException {
        //获得上传文件路径
        File uploadFile = new File("C:\\Users\\lingjun\\Desktop\\java小知识点.txt");

        //分块大小
        int chunkSize = 1024 * 1;
        //分块个数
        int chunkNum = (int) Math.ceil(uploadFile.length() * 1.0 / chunkSize);

        System.out.println("分块总数：" + chunkNum);
        //设置缓冲区大小

        FileReader read = new FileReader(uploadFile);

        //使用RandomAccessFile写入文件
        for (int i = 0; i < chunkNum; i++) {//使用RandomAccessFile读取文件
            System.out.println("分块路径" + i);
            //分块文件路径
            String chunkFilePath = "D:\\test\\" + i + ".txt";
            //分块文件
            File chunkFile = new File(chunkFilePath);

            System.out.println("分块路径：" + chunkFile);

         /*//分块文件不存在，创建分块文件
         if (!chunkFile.exists()) {
            chunkFile.createNewFile();
         }*/

            //分块文件写入
            FileWriter write = new FileWriter(chunkFile);

            char[] b = new char[2];
            int len = -1;
            while ((len = read.read(b)) != -1) {
                write.write(b, 0, len);
                System.out.println("字符：" + new String(b));
                System.out.println("分块文件大小：" + chunkFile.length());
                write.flush();
                if (chunkFile.length() >= chunkSize) {

                    break;
                }
            }

            write.close();

        }
        read.close();

    }

    //合并分块
    public static void mergeChunks() throws IOException {
        String chunkPath = "D:\\test\\";
        File chunkFolder = new File(chunkPath);

        //查找文件下的所有分块
        File[] files = chunkFolder.listFiles();

        //遍历所有分块并将其文件名数字从小到大排序
        Arrays.sort(files, new Comparator<File>() {

            @Override
            public int compare(File o1, File o2) {
                return Integer.parseInt(o1.getName()) - Integer.parseInt(o2.getName());
            }
        });

        System.out.println("分块文件：" + Arrays.toString(files));

        //创建文件写入流
        RandomAccessFile raf_write = new RandomAccessFile("D:\\test\\合并后的文件.avi", "rw");
        //显式将写入流指针移到顶部
        raf_write.seek(0);

        //合并文件
        for (File file : files) {
            RandomAccessFile raf_read = new RandomAccessFile(file, "r");

            //缓冲区大小
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = raf_read.read(b)) != -1) {
                raf_write.write(b, 0, len);
            }
            raf_read.close();
        }
    }


    //将文件分块上传至Minio中，然后进行合并
    public static void uploadChunks() throws IOException {
        //获得上传文件路径
        File uploadFile = new File("C:\\Users\\lingjun\\Videos\\屏幕录制\\屏幕录制 2024-08-29 155404.mp4");
        String chunkPath = "D:\\test\\";
        File chunkFolder = new File(chunkPath);
        //查找文件下的所有分块
        File[] files = chunkFolder.listFiles();
        Arrays.sort(files, Comparator.comparingInt(o -> Integer.parseInt(o.getName())));

        System.out.println("排序后的File：" + Arrays.toString(files));
        Integer[] count = {0};
        Arrays.stream(files).forEach(file -> {
            System.out.println(file);
            try {
                UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder().bucket("video").object("test/" + count[0]).filename(file.toString()).build();
                minioClient.uploadObject(uploadObjectArgs);

                System.out.println("上传成功：" + file.getName());
                count[0]++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //校验文件是否完成，完成则进行合并


    }
}
